// 封装axios
import axios from 'axios'
// 导入store
import store from '@/store'
import { Toast } from 'vant'
import router from '@/router'

const request = axios.create({
    baseURL: 'http://toutiao.itheima.net',
    // 解决精度丢失问题
})

// 解决响应拦截问题(更新token)
const refRequest = axios.create({
    baseURL: 'http://toutiao.itheima.net'
})

// 添加请求拦截器(config：当前请求的所有信息)
request.interceptors.request.use((config) => {
    const token = store.state.token.token
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

// 添加响应拦截
request.interceptors.response.use(response => {
    return response
}, async error => {
    // 判断错误的状态码是否是401
    const status = error.response.status
    if (status === 401) {
        const refresh_token = store.state.token.refresh_token

        try {
            const res = await refRequest({
                url: '/v1_0/authorizations',
                method: 'PUT',
                headers: {
                    Authorization: `Bearer ${refresh_token}`
                }
            })
            store.commit('setToken', {
                token: res.data.data.token,
                refresh_token: refresh_token
            })

            // 重新请求之前报错的请求
            return request(error.config)
        } catch {
            // 说明refresh_token也失效了
            // 跳转登录页面并提示登录过期
            Toast.fail('登录已过期')
            router.push('/login')
            // 返回一个错误信息
            return Promise.reject(new Error('refresh_token已过期'))
        }
    }
    return Promise.reject(error)
})

export default request